const app = getApp()
const util = require('../../../../../../utils/util.js');
const api = require('../../../../../../config/api.js');
Page({
  data: {
    circleid: "",
    themeid: "",
    contentType: "",//主题内容类型
    auxiliary: { "showAuthCode": false, "showAnswerOutTime": false, "showRanking": false, "showGetPrize": false },
    // 推荐信息
    ordThemeRecommend: {},
    // 主题推荐信息辅助对象
    ordThemeRecommendListAuxiliary: { "baobeiList": [], "circleList": [] },
    // 设置信息
    themeSetting: {},
    // 设置信息的辅助对象
    themeSettingAuxiliary: { "isAuthCode": false, "isAnswerOutTime": false, "isShowScore": false},
  },
  onLoad: function (options) {
    var _this = this;
    var themeid = options.themeid == null ? "" : options.themeid;
    _this.setData({
      contentType: options.contentType,
      ["themeSettingAuxiliary.timeStart"]: util.getDateStr(new Date(), 0),
      circleid: options.circleid,
      themeid: themeid
    })
    if (String(themeid).length <= 0) {
      _this.setData({
        themeSetting: JSON.parse(options.themeSetting)
      })
      _this.setThemeSettingAuxiliary();
      _this.loadRecommendedCircles();
    }else{
      // 获取问卷设置信息
      _this.getThemeSetting();
    }
  },

  /**
   * 获取主题设置信息
   */
  getThemeSetting: function(){
    console.log(133)
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.themeid = _this.data.themeid;
        data.access_token = res.access_token;
        util.post(api.Interest_GetThemeSettingApi, data).then(res => {
          if (res.code == 200) {
            _this.setData({
              themeSetting: res.result
            })
            _this.setThemeSettingAuxiliary();
            _this.loadRecommendedCircles();
          }
        })
      })
    }
  },
  /**
   * 初始化设置信息的辅助对象
   */
  setThemeSettingAuxiliary: function(){
    var _this = this;
    var themeSetting = _this.data.themeSetting;
    if (null != themeSetting.verificationCode && String(themeSetting.verificationCode).length > 0) {
      _this.setData({
        ["themeSettingAuxiliary.isAuthCode"]: true
      })
    }
    if (null != themeSetting.useTime && String(themeSetting.useTime).length > 0) {
      _this.setData({
        ["themeSettingAuxiliary.isAnswerOutTime"]: true
      })
    }
  },
  /**
   * 推荐的tabs切换
   */
  recommendTabsChange: function (event) {
    var _this = this;
    var index = event.detail.index;
    _this.setData({
      ["tabs.tabsActive"]: index
    })
  },
  /**
   * 答题验证码开关
   */
  changeAuthCode: function(e){
    var _this = this
    _this.setData({
      ["themeSettingAuxiliary.isAuthCode"]: e.detail.value
    })
  },
  /**
   * 答题验证码输入
   */
  inputAuthCode: function (e) {
    var _this = this
    var value = e.detail.value.replace(/\s+/g, '')
    _this.setData({
      ["themeSetting.verificationCode"]: value
    })
  },
  /**
   * 答题用时限制开关
   */
  changeAnswerOutTime: function (e) {
    var _this = this
    _this.setData({
      ["themeSettingAuxiliary.isAnswerOutTime"]: e.detail.value
    })
  }, 
  /**
   * 答题用时限制输入
   */
  inputAnswerOutTime: function (e) {
    var _this = this;
    var value = parseInt(e.detail.value);
    value = value > 0 ? value : "";
    _this.setData({
      ["themeSetting.useTime"]: value
    })
  },
  /**
   * 显示排行榜开关
   */
  changeRanking: function (e) {
    var _this = this
    _this.setData({
      ["themeSetting.isShowScore"]: e.detail.value ? 1 : 0
    })
  }, 
  /**
   * 获奖方式开关
   */
  changeGetPrize: function (e) {
    var _this = this;
    console.log(e.detail.value);
    _this.setData({
      ["themeSetting.isOpenReward"]: e.detail.value ? 1 : 0
    })
    var rewardWay = _this.data.themeSetting.rewardWay;
    if (rewardWay == null || String(rewardWay).length <= 0){
      _this.setData({
        ["themeSetting.rewardWay"]: 1
      })
    }
  }, 
  /**
   * 获奖类型
   */
  selecrGetPrizeType: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["themeSetting.rewardWay"]: index
    })
  }, 
  /**
   * 获奖的最低分值
   */
  inputGetPrizeMinScore: function (e) {
    var _this = this;
    var value = e.detail.value.replace(/\s+/g, '');
    value = value > 0 ? value : "";
    _this.setData({
      ["themeSetting.rewardScore"]: value
    })
  },
  /**
   * 获奖的最低获奖名次
   */
  inputGetPrizeRanking: function (e) {
    var _this = this;
    var value = e.detail.value.replace(/\s+/g, '');
    value = value > 0 ? value : "";
    _this.setData({
      ["themeSetting.rewardRanking"]: value
    })
  },
  /**
   * 开奖日期
   */
  getPrizeDateChange: function (e) {
    var _this = this
    _this.setData({
      ["themeSetting.lotteryDate"]: e.detail.value
    })
    var lotteryTime = _this.data.themeSetting.lotteryTime;
    if (lotteryTime == null || String(lotteryTime).length <= 0){
      _this.setData({
        ["themeSetting.lotteryTime"]: "09:00"
      })
    }
  },
  /**
   * 开奖时间
   */
  getPrizeTimeChange: function (e) {
    var _this = this
    _this.setData({
      ["themeSetting.lotteryTime"]: e.detail.value
    })
  },
  /**
   * 清空开奖时间
   */
  delectGetPrizeTime: function (e) {
    var _this = this;
    _this.setData({
      ["themeSetting.lotteryDate"]: '',
      ["themeSetting.lotteryTime"]: '',
    })
  },
  /**
   * 打开验证码介绍面板
   */
  openAuthCode: function () {
    var _this = this
    _this.setData({
      ["auxiliary.showAuthCode"]: true
    })
  },
  /**
   * 打开时间限制介绍面板
   */
  openAnswerOutTime: function () {
    var _this = this
    _this.setData({
      ["auxiliary.showAnswerOutTime"]: true
    })
  },
  /**
   * 打开排行榜介绍面板
   */
  openRanking: function () {
    var _this = this
    _this.setData({
      ["auxiliary.showRanking"]: true
    })
  },
  /**
   * 打开奖励方式介绍面板
   */
  openGetPrize: function () {
    var _this = this
    _this.setData({
      ["auxiliary.showGetPrize"]: true
    })
  },
  /**
  * 打开选择奖品面板
  */
  openRecommend: function () {
    var _this = this
    _this.setData({
      ["auxiliary.showRecommend"]: true
    })
  },
  /**
   * 关闭面板
   */
  closeMC: function () {
    var _this = this
    _this.setData({
      ["auxiliary.showAuthCode"]: false,
      ["auxiliary.showAnswerOutTime"]: false,
      ["auxiliary.showRanking"]: false,
      ["auxiliary.showGetPrize"]: false,
      ["auxiliary.showRecommend"]: false,
    })
  },

  /**
   * 加载推荐圈子
   */
  loadRecommendedCircles: function () {
    var _this = this;
    var themeSetting = _this.data.themeSetting;
    var isOpenReward = themeSetting.isOpenReward;
    var rewardType = themeSetting.rewardType;
    var rewardDataId = themeSetting.rewardDataId;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.circleid = _this.data.circleid;
        data.access_token = res.access_token;
        util.post(api.Interest_getUserRecommendInfoApiUrl, data).then(res => {
          if (res.code == 200) {
            var json = res.result.json;
            var circleList = json.circleList;
            var baobeiList = json.baobeiList;
            _this.setData({
              ["ordThemeRecommendListAuxiliary.circleList"]: circleList,
              ["ordThemeRecommendListAuxiliary.baobeiList"]: baobeiList
            })
            var ordThemeRecommend = {};
            if (rewardType == 1){
              for (var j = 0; j < circleList.length; j++) {
                if (rewardDataId == circleList[j].id) {
                  ordThemeRecommend.recommendId = circleList[j].id;
                  ordThemeRecommend.title = circleList[j].title;
                  ordThemeRecommend.peopleNumber = circleList[j].renshu;
                  ordThemeRecommend.clockNumber = circleList[j].qiandao;
                  ordThemeRecommend.money = circleList[j].showCirclesMoney;
                  ordThemeRecommend.image = circleList[j].beijing;
                  ordThemeRecommend.isCommission = circleList[j].isCommission;
                  ordThemeRecommend.recommendType = "1";//1圈子  2宝贝
                  _this.setData({
                    ["ordThemeRecommendListAuxiliary.circleList[" + j + "].circlesChecked"]: true
                  })
                }
              }
            } else if (rewardType == 2){
              for (var j = 0; j < baobeiList.length; j++) {
                if (rewardDataId == baobeiList[j].id) {
                  _this.setData({
                    ["ordThemeRecommendListAuxiliary.baobeiList[" + j + "].circlesChecked"]: true
                  })
                }
              }
            }
            _this.setData({
              ordThemeRecommend: ordThemeRecommend
            })
          }
        })
      })
    }
  },

  /**
   * 推荐信息选中事件
   */
  recommendClick: function (e) {
    var _this = this;
    var type = e.currentTarget.dataset.type;
    var index = e.currentTarget.dataset.index;
    var circleList = _this.data.ordThemeRecommendListAuxiliary.circleList;
    var baobeiList = _this.data.ordThemeRecommendListAuxiliary.baobeiList;
    for (var i = 0; i < circleList.length; i++) {
      _this.setData({
        ["ordThemeRecommendListAuxiliary.circleList[" + i + "].circlesChecked"]: false
      })
    }
    for (var i = 0; i < baobeiList.length; i++) {
      _this.setData({
        ["ordThemeRecommendListAuxiliary.baobeiList[" + i + "].circlesChecked"]: false
      })
    }
    if (type == 1) {
      var circlesChecked = circleList[index].circlesChecked;
      _this.setData({
        ["ordThemeRecommendListAuxiliary.circleList[" + index + "].circlesChecked"]: !circlesChecked
      })
    } else if (type == 2) {
      var circlesChecked = baobeiList[index].circlesChecked;
      _this.setData({
        ["ordThemeRecommendListAuxiliary.baobeiList[" + index + "].circlesChecked"]: !circlesChecked
      })
    }
  },

  /**
   * 推荐项目确认动作
   */
  recommendConfirm: function () {
    var _this = this;
    var ordThemeRecommend = {};
    var rewardType = "";
    var rewardDataId = "";
    var circleList = _this.data.ordThemeRecommendListAuxiliary.circleList;
    var baobeiList = _this.data.ordThemeRecommendListAuxiliary.baobeiList;
    for (var i = 0; i < circleList.length; i++) {
      if (circleList[i].circlesChecked) {
        ordThemeRecommend.recommendId = circleList[i].id;
        ordThemeRecommend.title = circleList[i].title;
        ordThemeRecommend.peopleNumber = circleList[i].renshu;
        ordThemeRecommend.clockNumber = circleList[i].qiandao;
        ordThemeRecommend.money = circleList[i].showCirclesMoney;
        ordThemeRecommend.image = circleList[i].beijing;
        ordThemeRecommend.isCommission = circleList[i].isCommission;
        ordThemeRecommend.recommendType = "1";//1圈子  2宝贝
        rewardType = "1";
        rewardDataId = circleList[i].id;
      }
    }
    for (var i = 0; i < baobeiList.length; i++) {
      if (baobeiList[i].circlesChecked) {

      }
    }
    _this.setData({
      ordThemeRecommend: ordThemeRecommend,
      ["themeSetting.rewardType"]: rewardType,
      ["themeSetting.rewardDataId"]: rewardDataId,
    })
    _this.closeMC();
  },

  /**
   * 删除奖品
   */
  deleteRecommend: function(){
    var _this = this;
    var rewardType = _this.data.themeSetting.rewardType;
    var rewardDataId = _this.data.themeSetting.rewardDataId;
    var circleList = _this.data.ordThemeRecommendListAuxiliary.circleList;
    var baobeiList = _this.data.ordThemeRecommendListAuxiliary.baobeiList;
    if (rewardType == 1){
      for (var i = 0; i < circleList.length; i++) {
        _this.setData({
          ["ordThemeRecommendListAuxiliary.circleList[" + i + "].circlesChecked"]: false
        })
      }
    } else if (rewardType == 2){
      for (var i = 0; i < baobeiList.length; i++) {
        _this.setData({
          ["ordThemeRecommendListAuxiliary.baobeiList[" + i + "].circlesChecked"]: false
        })
      }
    }
    _this.setData({
      ordThemeRecommend: {},
      ["themeSetting.rewardType"]: "",
      ["themeSetting.rewardDataId"]: "",
    })
  },

  /**
   * 保存
   */
  submit: function(){
    var _this = this;
    var themeid = _this.data.themeid;
    var circleid = _this.data.circleid;
    var themeSetting = _this.data.themeSetting;
    if (!_this.themeSettingCheck()){
      return false;
    }
    if(themeid == null || String(themeid).length <= 0){
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2];  //上一个页面
      prevPage.setData({
        themeSetting: themeSetting
      });
      wx.navigateBack({
        delta: 1
      })
    }else{
      // 调用数据库保存
      _this.updateThemeSetting();
    }
  },

  /**
   * 保存主题
   */
  updateThemeSetting: function(){
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = _this.data.themeSetting;
        data.openid = openid;
        data.themeid = _this.data.themeid;
        data.access_token = res.access_token;
        util.post(api.Interest_UpdateThemeSettingApi, data).then(function (res) {
          if (res.code == 200) {
            wx.navigateBack({
              delta: 1
            })
          }else{
            util.showToast(res.message, "none");
          }
        })
      })
    }
  },

  /**
   * 校验主题设置信息
   */
  themeSettingCheck: function () {
    var _this = this;
    var themeSetting = _this.data.themeSetting;
    var themeSettingAuxiliary = _this.data.themeSettingAuxiliary;
    var isAuthCode = _this.data.themeSettingAuxiliary.isAuthCode;
    var isAnswerOutTime = _this.data.themeSettingAuxiliary.isAnswerOutTime;
    var isShowScore = _this.data.themeSettingAuxiliary.isShowScore;
    var isOpenReward = themeSetting.isOpenReward;
    var verificationCode = themeSetting.verificationCode;
    var useTime = themeSetting.useTime;
    var lotteryTime = themeSetting.lotteryTime;
    var lotteryDate = themeSetting.lotteryDate;
    var rewardDataId = themeSetting.rewardDataId;
    var rewardWay = themeSetting.rewardWay;
    var rewardScore = themeSetting.rewardScore;
    var rewardRanking = themeSetting.rewardRanking;
    if (isAuthCode && (verificationCode == null || String(verificationCode).length <= 0)) {
      util.showToast("请输入答题验证码", "none");
      return false;
    }
    console.log(useTime)
    if (isAnswerOutTime && (useTime == null || String(useTime).length <= 0)) {
      util.showToast("请输入用时限制", "none");
      return false;
    }
    if (isOpenReward == 1 && (lotteryDate == null || String(lotteryDate).length <= 0)) {
      util.showToast("请选择开奖日期", "none");
      return false;
    }
    if (isOpenReward == 1 && (rewardDataId == null || String(rewardDataId).length <= 0)) {
      util.showToast("请选择奖品", "none");
      return false;
    }
    if (isOpenReward == 1 && rewardWay == 2 && (rewardScore == null || String(rewardScore).length <= 0)) {
      util.showToast("请输入成绩", "none");
      return false;
    }
    if (isOpenReward == 1 && rewardWay == 3 && (rewardRanking == null || String(rewardRanking).length <= 0)) {
      util.showToast("请输入排行", "none");
      return false;
    }
    if (!isAuthCode) {
      _this.setData({
        ["themeSetting.verificationCode"]: null
      })
    }
    if (!isAnswerOutTime) {
      _this.setData({
        ["themeSetting.useTime"]: null
      })
    }
    if (isOpenReward == 0) {
      _this.setData({
        ["themeSetting.lotteryDate"]: null,
        ["themeSetting.rewardDataId"]: null,
        ["themeSetting.lotteryTime"]: null,
        ["themeSetting.rewardType"]: null,
        ["themeSetting.rewardRanking"]: null,
        ["themeSetting.rewardScore"]: null,
        ["themeSetting.rewardWay"]: null,
      })
    }else{
      if (rewardWay == 1){
        _this.setData({
          ["themeSetting.rewardScore"]: null,
          ["themeSetting.rewardRanking"]: null,
        })
      }else if (rewardWay == 2){
        _this.setData({
          ["themeSetting.rewardRanking"]: null,
        })
      } else if (rewardWay == 3){
        _this.setData({
          ["themeSetting.rewardScore"]: null,
        })
      }
    }
    return true;
  }
})